<template>
	<view class="page" >
    <view class="lunbo">
      <u-swiper  :list="list3" indicator indicatorMode="line" circular height="300px"></u-swiper>
    </view>
		<view class="form-content">
			<u--form ref="uForm" label-position="left" :model="form" :rules="rules">
        <u-form-item required label="更换头像" prop="avatar" border-bottom>
					<u-upload
            v-model="form.avatar"
            :fileList="fileList1"
            @afterRead="afterRead"
            @delete="deletePic"
            name="1"
          ></u-upload>
				</u-form-item>
        <u-form-item required label="账号" prop="phone" border-bottom>
					<u--input v-model="form.phone" border="none" placeholder="请输入账号"></u--input>
				</u-form-item>
        <u-form-item required label="密码" prop="password" border-bottom>
					<u-input
						v-model="form.password"
						:password="isPassword"
						border="none"
						placeholder="请输入密码"
					>
						<template slot="suffix">
							<view @click="isPassword = !isPassword">
								<i v-if="isPassword" class="iconfont icon-biyanjing preicon"></i>
								<i v-else class="iconfont icon-yanjing preicon"></i>
							</view>
						</template>
					</u-input>
				</u-form-item>
				<u-form-item required label="昵称" prop="username" border-bottom>
					<u--input v-model="form.username" border="none" placeholder="请输入昵称"></u--input>
				</u-form-item>
				<u-form-item required label="性别" prop="sex" border-bottom @click="openSelect">
					<u--input
						v-model="form.sex"
						disabled
						disabled-color="#ffffff"
						placeholder="请选择性别"
						border="none"
					></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="签名" prop="sign">
					<u--input v-model="form.sign" border="none" placeholder="请输入签名"></u--input>
				</u-form-item>
			</u--form>
		</view>
		<view class="button" @click="toUpdata">修改</view>
    <view class="button1" @click="toOut">退出</view>
    <view class="button2" @click="toDelete">注销</view>
		<u-action-sheet
			:show="showSex"
			:actions="actions"
			@close="showSex = false"
			@select="sexSelect"
		></u-action-sheet>
	</view>
</template>

<script>

import { baseUrl } from '@/config';

export default {
	data() {
		return {
      user:[],
      fileList1: [],
      id:0,
      list3: [
          baseUrl+'/app/005.jpg',
          baseUrl+'/app/004.jpg',
          baseUrl+'/app/003.jpg'
        ],
			isPassword: true,
			form: {
        avatar:'',
				username: '',
				password: '',
				phone: '',
				sex:'',
				sign:''
			},
			actions: [
				{
					name: '男'
				},
				{
					name: '女'
				}
			],
			rules: {
        avatar: [
					{
						required: true,
						message: '请上传头像',
						trigger: ['blur', 'change']
					}
				],
				phone: [
            {
              required: true, 
              message: '请输入手机号',
              trigger: ['change','blur'],
            },
            {
              validator: (rule, value, callback) => {
                return uni.$u.test.mobile(value);
              },
              message: '手机号码不正确',
              trigger: ['change','blur'],
            }
          	],
				username: [
					{
						required: true,
						message: '请输入昵称',
            trigger: ['blur', 'change']
					}
				],
        sex: {
					type: 'string',
					max: 1,
					required: true,
					message: '请选择男或女',
					trigger: ['blur', 'change']
				},
				password: [
					{
            type: 'string',
				    min: 6,
            max:9,
						required: true,
						message: '请输入6-9位数的密码',
						trigger: ['blur', 'change']
					}
				]
			},
			showSex: false
		};
	},
	watch: {
	},
  onShow(){
    this.id =  uni.getStorageSync('user').data[0].id 
        // this.id =  uni.getStorageSync('user').date.id 

    this.getUser()
  },
	onReady() {
		this.$refs.uForm.setRules(this.rules)
	},
	methods: {
    getUser(){
      uni.request({
        url: baseUrl+'/v1/user/idSearch', 
        data:{
          id:this.id
        },
        success: (res) => {
          this.user = res.data.data[0]
              this.form.username = this.user.username
              this.form.password = this.user.password
              this.form.phone = this.user.phone
              this.form.sex = this.user.sex
              this.form.sign = this.user.sign
              this.id = this.user.id
              // this.form.avatar =this.user.avatar
        }
                });
    },
    deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1);
      },
      async afterRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file);
        let fileListLen = this[`fileList${event.name}`].length;
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: "uploading",
            message: "上传中",
          });
        });
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url);
          let item = this[`fileList${event.name}`][fileListLen];
          this[`fileList${event.name}`].splice(
            fileListLen,
            1,
            Object.assign(item, {
              status: "success",
              message: "",
              url: result,
            })
          );
          fileListLen++;
        }
      },
    uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: "http://127.0.0.1:3000/v1/upload/upload", // 仅为示例，非真实的接口地址
            filePath: url,
            name: "file",
            success: (res) => {
              this.form.avatar= res.data.slice(42,-2)
              setTimeout(() => {
                resolve(res.data.data);
              }, 1000);
            },
          });
        });
      },
    toDelete(){
      uni.request({
          data: {
          id : this.id
        }, 
        url: baseUrl+'/v1/user/userDelete',
        success: () => {
          uni.removeStorageSync('user');
          uni.showToast({
                title: '注销成功',
                duration: 1000
              });
              setTimeout(function() {
                uni.redirectTo({
                  url: "/pages/login/index"
                })
				      }, 1500)
          }
        });
    },
    toOut(){
      uni.removeStorageSync('user');
      uni.navigateTo({
        url:'/pages/login/index'
      })
    },
    toUpdata(){
      this.$refs.uForm.validate().then(res => {
				if (res) {
					uni.request({
          url:baseUrl+"/v1/user/userUpdate",
          method: 'POST',
          header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
 					data: {
            id:this.id,
 						phone: this.form.phone,
 						password: this.form.password,
            username:this.form.username,
            sex:this.form.sex,
            sign:this.form.sign,
            avatar:this.form.avatar
 					},
          success:(res)=>{
            console.log(res.data);
            uni.removeStorageSync('user');
            uni.setStorageSync('user',res.data)
            if (res.data.code == 200) {
					    uni.setStorageSync('user',res.data) 
              uni.showToast({
                    title: '修改成功',
                    duration: 1000
                });
              setTimeout(function() {
                uni.navigateTo({
	                      url: '/pages/login/index'
                      });
              }, 1500)
                  
 				} else {
 					uni.showToast({
 						title: "注册失败!",
 						icon: 'none',
 						duration: 2000
 					})
 				}
          }
 				})
				}
			});
        
    },
		openSelect() {
			this.showSex = true;
			uni.hideKeyboard();
		},
		sexSelect({ name }) {
			this.form.sex = name;
		}
	}
};
</script>

<style scoped lang="scss">
.page {
	background-size: 100% 100%;
	padding: 64rpx 32rpx;
	height: calc(100vh - 88rpx);
	box-sizing: border-box;
	.form-content {
		height: 80%;
		background: #ffffff;
		border-radius: 16rpx;
		padding: 60rpx 40rpx 80rpx;
		position: relative;
	}
	.button2 {
		position: absolute;
		// z-index: 667;
		bottom: -130px;
		left:40rpx;
		right: 40rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 16rpx;
		color: #ffffff;
		background: #bd173e;
		margin: 40rpx auto 0;
		text-align: center;
	}
  .button1 {
		position: absolute;
		// z-index: 667;
		bottom: -80px;
		left:40rpx;
		right: 40rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 16rpx;
		color: #ffffff;
		background: #ffb80f;
		margin: 40rpx auto 0;
		text-align: center;
	}
  .button {
		position: absolute;
		bottom: -30px;
		left:40rpx;
		right: 40rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 16rpx;
		color: #ffffff;
		background: #76e00f;
		margin: 40rpx auto 0;
		text-align: center;
	}


}
</style>
